<?php

namespace App\Plugins\Wechat;

use App\Services\Repo\UserRepo;
use Illuminate\Support\Facades\Redis;

class Client
{
    /**
     * @param int $uin
     * @return int
     */
    static public function isActive($uin) {
        $channel = sprintf(SETTING::COMMAND_QUEUE, $uin, 'ping');
        $r = Redis::publish($channel, 'ping');
        if ($r) {
            $clientInfoKey = sprintf(SETTING::CLIENT_INFO, $uin);
            $status = Redis::hget($clientInfoKey, 'status');
            return $status;
        }
        return 0;
    }

    static public function syncContacts($uin) {
        $key = sprintf(SETTING::CLIENT_INFO, $uin);
        $raw = Redis::hget($key, 'contacts');
        $data = json_decode($raw, 1);
        if ($data) {
            $ret_data = new \stdClass();
            $ret_data->contacts = collect($data['contacts']);
            $ret_data->groups = collect($data['groups']);
            return $ret_data;
        }
        return null;
    }

    static public function getUserInfo($uin) {
        $key = sprintf(SETTING::CLIENT_INFO, $uin);
        $raw = Redis::hget($key, 'User');
        if ($raw) {
            return json_decode(str_replace("'", '"', $raw));
        }
        return null;
    }

    static public function updateInfo($uin) {
        $channel = sprintf(SETTING::COMMAND_QUEUE, $uin, 'update_info');
        $r = Redis::publish($channel, 1);
        return $r;
    }

    static public function removeInfo($uin) {
        $key = sprintf(SETTING::CLIENT_INFO, $uin);
        Redis::del([$key]);
        $channel = sprintf(SETTING::COMMAND_QUEUE, $uin, 'stop');
        $r = Redis::publish($channel, 1);
        return $r;
    }

    static public function contactExists($uin, $searchName)
    {
        $contacts = static::syncContacts($uin);
        if (is_null($contacts) OR empty($contacts)) return false;

    }
}
